package fun.formoji.commons.config;

import com.alibaba.fastjson.JSON;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import fun.formoji.commons.model.RestResponse;
import fun.formoji.commons.model.ServiceCode;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * <code>CustomFeignDecoder</code>
 * <desc>
 * 描述：
 * <desc/>
 * <b>Creation Time:</b> 2021/5/6 14:13.
 *
 * @author hshe
 */
public class FeignResponseDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (response.body() == null) {
            throw new DecodeException(response.status(), "没有返回有效的数据", response.request());
        }
        String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        //对结果进行转换
        RestResponse restResponse = (RestResponse) JSON.parseObject(bodyStr, type);
        //如果返回错误，且为内部错误，则直接抛出异常
        if (restResponse.getCode() != ServiceCode.SUCCESS.getCode()) {
            // throw new DecodeException(response.status(), "接口返回错误：");
        }
        return restResponse.getData();
    }
}
